<?php

namespace app\service;

use app\model\Auth;
use app\model\Role;
use app\traits\Singleton;
use think\facade\Db;

class RoleService
{
    use Singleton;
    public function getRoleList($page = 1,$pageSize = 10)
    {
        $model = Role::where("is_delete", "=", 0)
            ->order('id', 'desc');

        $paginator = $model
            ->page($page)
            ->paginate($pageSize);

        $data = array_map(function ($item) {
            return $item;
        }, $paginator->getCollection()->toArray());

        return [
            "list" => $data,
            "total" => $paginator->total()
        ];
    }

    public function getRoleById($id)
    {
        return Role::where('id', $id)->find();
    }
    public function createRole($name, $description, $status)
    {
        return Role::create([
            'name' => $name,
            'description' => $description
        ]);
    }

    public function updateRole($id, $name, $description, $status)
    {
        return Role::where('id', $id)->update([
            'name' => $name,
            'description' => $description,
            'status' => $status,
        ]);
    }

    public function deleteRole($id)
    {
        return Role::where('id', $id)->save([
            "is_delete" => 1,
            "delete_time" => time()
        ]);
    }

    public function createRoleMenus($id, $menuIds)
    {
        return Db::transaction(function () use ($id, $menuIds) {

            $oldMenuIds = Auth::where("role_id", $id)->column("menu_id");
            $delDiff = array_diff($oldMenuIds, $menuIds);
            if (!empty($delDiff)) {
                Auth::where("role_id", $id)->whereIn("menu_id", $delDiff)->delete();
            }

            $addDiff = array_diff($menuIds, $oldMenuIds);
            if (!empty($addDiff)) {
                foreach ($addDiff as $menuId) {
                    Auth::create([
                        "role_id" => $id,
                        "menu_id" => $menuId
                    ]);
                }
            }
            return true;
        });
    }

    public function getRoleMenus($id)
    {
         $menuIds = Auth::where("role_id", $id)->column("menu_id");
         return [
             "role_id" => $id,
             "menu_ids" => $menuIds
         ];
    }
}
